package Service;

import Entity.File;

import java.util.ArrayList;
import java.util.List;

public class BinaryStream {
    public static List<Byte> lock( String key, List<Byte> fileStream) {
        List<Byte> returnFileStream = new ArrayList<> ();
        byte[] keycode = key.getBytes ();
        int keycodeIndex = 0;
        for (int i = 0; i < fileStream.size (); i++) {
            returnFileStream.set ( i , (byte) ( fileStream.get ( i ) ^ keycode[keycodeIndex] ) );
            keycodeIndex++;
            if (keycodeIndex > keycode.length - 1) {
                keycodeIndex = 0;
            }
        }
        return returnFileStream;
    }

    public static List<File> splitToFile ( int size , List<Byte> fileStream , String FileName ) {
        List<File> returnFiles = new ArrayList<> ();
        int index = 0;
        for (int i = 0; i < fileStream.size (); i += size) {
            File tmpFile = new File ();
            tmpFile.setFileStream ( new ArrayList<> ( fileStream.subList ( i , Math.min ( fileStream.size () , i + size - 1 ) ) ) );
            tmpFile.setFileName ( FileName + String.valueOf ( index ) );
            returnFiles.add ( tmpFile );
            index++;
        }
        return returnFiles;
    }

    public static File mergeIntoStream ( String fileName , List<File> files ) {
        File returnFile = new File ();
        List<Byte> byteList = new ArrayList<> ();
        for (int i = 0; i < files.size (); i++) {
            byteList.addAll ( files.get ( i ).getFileStream () );
        }
        returnFile.setFileName ( fileName );
        returnFile.setFileStream ( byteList );
        return returnFile;
    }
}


